#pragma once

#include <iostream>
#include <functional>
#include <cstring>
#include <memory>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>

#include "Log.hpp"
#include "InetAddr.hpp"

namespace socket_ns
{
    class Socket;
    using SockPtr = std::shared_ptr<Socket>;
    
    static const int gbacklog = 8;
    // 模版方法类模式
    class Socket
    {
    public:
        virtual void CreatSocketOrDie() = 0;
        virtual void CreatBindOrDie(uint16_t port) = 0;
        virtual void CreatListenOrDie(int backlog = gbacklog) = 0;
        virtual SockPtr Accepter(InetAddr *clientaddr) = 0;
        virtual bool Connector(const std::string &peerip, uint16_t peerport) = 0;
        virtual int Sockfd() = 0;
        virtual void Close() = 0;
        virtual ssize_t Recv(std::string *out) = 0;
        virtual ssize_t Send(const std::string &out) = 0;

    public:
        void BuildListenSocket(uint16_t port)
        {
            CreatSocketOrDie();
            CreatBindOrDie(port);
            CreatListenOrDie();
        }
        bool BuildClientSocket(const std::string &peerip, uint16_t peerport)
        {
            CreatSocketOrDie();
            return Connector(peerip, peerport);
        }
        // void BuildUdpSocket()
        // {
        // }
    };

    enum
    {
        SOCKET_ERROR = 1,
        BIND_ERROR,
        LISTEN_ERROR
    };

    using namespace log_ns;    

    class TcpSocket : public Socket
    {
    public:
        TcpSocket(int sockfd) // 这里是给监听套接字获取到连接的新sockfd用
            : _sockfd(sockfd)
        {
        }
        TcpSocket() {}
        ~TcpSocket()
        {
        }
        void CreatSocketOrDie() override
        {
            // 1.创建socket
            _sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0)
            {
                LOG(FATAL, "socket creat error!\n");
                exit(SOCKET_ERROR);
            }
            LOG(INFO, "socket creat success, sockfd: %d\n", _sockfd); // 3
        }
        void CreatBindOrDie(uint16_t port) override
        {
            struct sockaddr_in local;
            memset(&local, 0, sizeof local);

            local.sin_family = AF_INET; // 指定ip地址为IPV4
            local.sin_port = htons(port);
            local.sin_addr.s_addr = INADDR_ANY; // 服务器端进程任意IP地址绑定

            // 2.bind sockfd 和 socket addr
            if (::bind(_sockfd, (struct sockaddr *)&local, sizeof local) < 0)
            {
                LOG(FATAL, "bind error!\n");
                exit(BIND_ERROR);
            }
            LOG(INFO, "bind success! sockfd: %d\n", _sockfd);
        }
        void CreatListenOrDie(int backlog = gbacklog) override
        {
            // 3.因为tcp是面相连接的，tcp需要未来不断的能够做到获取连接
            if (::listen(_sockfd, gbacklog) < 0)
            {
                LOG(FATAL, "listen error!\n");
                exit(LISTEN_ERROR);
            }
            LOG(INFO, "listen success!\n");
        }
        SockPtr Accepter(InetAddr *clientaddr) override
        {
            // 4.获取新连接
            struct sockaddr_in client;
            socklen_t len = sizeof client;
            int sockfd = ::accept(_sockfd, (struct sockaddr *)&client, &len); // 监听套接字
            if (sockfd < 0)
            {
                return nullptr;
            }
            *clientaddr = InetAddr(client);
            // LOG(INFO, "get a new link, client info: %s, sockfd is: %d\n", clientaddr->AddrStr().c_str(), sockfd);

            return std::make_shared<TcpSocket>(sockfd); // C++14
        }
        bool Connector(const std::string &peerip, uint16_t peerport) override
        {
            struct sockaddr_in server;
            memset(&server, 0, sizeof server);
            server.sin_family = AF_INET;
            server.sin_port = htons(peerport);
            // server.sin_addr.s_addr =
            ::inet_pton(AF_INET, peerip.c_str(), &server.sin_addr);
            int n = ::connect(_sockfd, (struct sockaddr *)&server, sizeof server);
            if (n < 0)
            {
                std::cerr << "connect socket failed!" << std::endl;
                return false;
            }
            return true;
        }
        int Sockfd()
        {
            return _sockfd;
        }
        void Close()
        {
            if (_sockfd > 0)
                ::close(_sockfd);
        }
        ssize_t Recv(std::string *out) override
        {
            char inbuffer[4096];
            ssize_t n = ::recv(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0);
            if (n > 0)
            {
                inbuffer[n] = 0;
                *out += inbuffer;
            }
            return n;
        }
        ssize_t Send(const std::string &in) override
        {
            return ::send(_sockfd, in.c_str(), in.length(), 0);
        }

    private:
        int _sockfd; // 可以是listensock，也可以是普通sockfd
    };

    class UdpSocket : public Socket
    {
    };
}